#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;

//string的构造
void test0(){
    string str1;
    cout << str1 << endl;

    string str2("hello");
    cout << str2 << endl;
    string str3("hello",3);
    cout << str3 << endl;

    string str4(str2,1,3);
    cout << str4 << endl;

    string str5(5,'a');
    cout << str5 << endl;


    /* char * p = str2.begin(); */
    string::iterator it = str2.begin();
    //迭代器视为广义的指针
    //begin()获取首迭代器
    //end()获取尾后迭代器
    string str6(str2.begin(),--str2.end());
    cout << str6 << endl;


    char arr[6] = "world";
    arr;
    arr + 3;
    string str7(arr,arr + 3);
    cout << str7 << endl;
}

//string的拼接
void test1(){
    string str1("hello,");
    string str2("world");
    string str3 = str1 + str2 + "!!!" + '!';
    cout << str3 << endl;

    /* &(str1 + str2); */
}

//string的常用操作
void test2(){
    /* const char * pstr = "hello"; */
    string str1("hello");
    printf("%s\n",str1.c_str());
    cout << str1.empty() << endl;
    //获取有效的字符数，不包含结尾空字符
    cout << "str1.size:" << str1.size() << endl;

    string str2;
    cout << str2.empty() << endl;
    cout << "str2.size:" << str2.size() << endl;

    str2.push_back('a');
    str2.push_back('a');
    str2.push_back('a');
    cout << str2 << endl;
    cout << "str2.size:" << str2.size() << endl;

    str2.append(5,'b');
    cout << str2 << endl;

    str2.append(",hello");
    cout << str2 << endl;

    /* string str3(",world"); */
    string str3(",world",1,5);
    cout << &str2 << endl;
    cout << &(str2.append(str3)) << endl;
    cout << str2 << endl;
}

//string的查找操作
void test3(){
    string str1("hello");
    string str2("hel");
    size_t pos = str1.find(str2,1);
    cout << pos << endl;

    pos = str1.find('e',2);
    cout << pos << endl;

    pos = str1.find("ol",2,1);
    cout << pos << endl;
}

//重点：string的遍历
void test4(){
    string str1("hello");
    /* cout << str1[0] << endl; */
    //方式一：通过下标遍历
    for(size_t idx = 0; idx < str1.size(); ++idx)
    {
        cout << str1[idx] << " ";
    }
    cout << endl;

    //方式二：增强for循环 —— 重点！
    //可以自动完成容器中元素的遍历
    //一般与auto连用，auto可以自动推导类型
    //ch代表容器中的元素，str1是容器在代码中的名字
    //引用符号的意义——在for循环中使用的ch代表元素本身
    //如果没有引用，ch就是容器中元素的副本
    /* for(auto & ch : str1){ */
    /*     ++ch; */
    /* } */
    /* cout << endl; */

    for(auto & ch : str1){
        cout << ch << " ";
    }
    cout << endl;


    //方式三：迭代器方式
    /* string::iterator it = str1.begin(); */
    auto it = str1.begin(); 
    for(;it != str1.end(); ++it){
        cout << *it << " ";
    }
    cout << endl;
}


int main(void){
    test4();
    return 0;
}
